var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var BodyParser = require('body-parser');
var RedisStore = require('connect-redis')(session);
var log4js = require('log4js');

var Config = require('./config');

var app = express();
process.on('uncaughtException', function (err) {
    console.log('Caught exception: ', err);
});
// view engine setup
app.set('views', path.join(__dirname, 'views/admins'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
//config
log4js.configure(Config.Log4js.Admin);
var logger = log4js.getLogger('access');
app.use(log4js.connectLogger(logger, {level: 'info'}));
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));

//cookies & session
app.use(session({
    store: new RedisStore(Config.Redis.Session),
    secret: Config.Common.Session_Ssecret,
    resave: true,
    saveUninitialized: false,
    cookie: {domain: Config.Common.Domain}
}));

app.use('/', require('./routes/admins'));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
